package com.ys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.ys.config.MyConfig;
import com.ys.entity.amazonorder.TpAmazonSellerReport;
import com.ys.entity.base.BaseEntity;
import com.ys.entity.business.TpAmazonShopExchangeRate;
import com.ys.enume.RegionEnum;
import com.ys.enume.amazonorder.TpAmazonShopReportEnum;
import com.ys.service.amazonorder.TpAmazonSellerReportService;
import com.ys.util.amazon.AmazonUtil;

/**
 * Hello world!
 *
 */
@EnableScheduling
@SpringBootApplication(
	exclude = {
		DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class //  排除数据源自动装配
	}
)
//@SpringBootApplication
@EnableCaching
@MapperScan(basePackages = "com.ys.mapper")
@ComponentScan(basePackages={"com.ys"})
@EnableTransactionManagement
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class App {
	public static void main(String[] args) {
		System.out.println("Hello World!");
		ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
		BaseEntity._ys_ac = context;

        // 执行亚马逊订单报告更新（英国）
		{
			Thread t = new Thread(() -> {
				System.out.println("开始线程---执行亚马逊订单报告更新（英国）");
		        try {
					updateReport(context, RegionEnum.EUROPE.getCode());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
			t.start();
		}
		
        // 读取亚马逊店铺订单报告并更新（英国）
		{
			Thread t = new Thread(() -> {
				System.out.println("开始线程---读取亚马逊店铺订单报告并更新（美国）");
		        try {
		            readReport(context, RegionEnum.EUROPE.getCode());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
			t.start();
		}

        // 执行亚马逊订单报告更新（美国）
		{
			Thread t = new Thread(() -> {
				System.out.println("开始线程---执行亚马逊订单报告更新（美国）");
		        try {
					updateReport(context, RegionEnum.NORTH.getCode());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
			t.start();
		}
		
        // 读取亚马逊店铺订单报告并更新（美国）
		{
			Thread t = new Thread(() -> {
				System.out.println("开始线程---读取亚马逊店铺订单报告并更新（美国）");
		        try {
		            readReport(context, RegionEnum.NORTH.getCode());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
			t.start();
		}
	}

	
	/*
	 * 更新报告
	 */
	public static void updateReport(ConfigurableApplicationContext context, String regionCode) throws InterruptedException {

		TpAmazonSellerReportService tpAmazonShopReportService = (TpAmazonSellerReportService) context.getBean(TpAmazonSellerReportService.class);
		while (true) {
	    	
			Map<String, AWSAuthenticationCredentials> MAP_REGION_Credentials = AmazonUtil.getCredentials();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AmazonUtil.getProvider();
			
			// 更新每个店铺订单报告的文件ID
			List<TpAmazonSellerReport> listTpAmazonShopReport = new TpAmazonSellerReport()
					.setRegionCode(regionCode)
					.setState(TpAmazonShopReportEnum.State.NO_HANDLE.value)
					.queryList();
			for(TpAmazonSellerReport tpAmazonShopReport : listTpAmazonShopReport) {
				Long id = tpAmazonShopReport.getId();
				try {
					tpAmazonShopReportService.updateReportDocumentId(id, MAP_REGION_Credentials, awsAuthenticationCredentialsProvider);;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			Thread.sleep(20000L);
			continue;
		}
	}
	
	/*
	 * 读取报告并更新
	 */
	public static void readReport(ConfigurableApplicationContext context, String regionCode) throws InterruptedException {

    	TpAmazonSellerReportService tpAmazonShopReportService = (TpAmazonSellerReportService) context.getBean(TpAmazonSellerReportService.class);

		List<TpAmazonShopExchangeRate> listTpAmazonShopExchangeRate = new TpAmazonShopExchangeRate().queryList();
		Map<String, TpAmazonShopExchangeRate> MAP_CODE_RATE = new HashMap<String, TpAmazonShopExchangeRate>();
		for(TpAmazonShopExchangeRate rate : listTpAmazonShopExchangeRate) {
			MAP_CODE_RATE.put(rate.getCode(), rate);
		}
		
		while (true) {
			
			Map<String, AWSAuthenticationCredentials> MAP_REGION_Credentials = AmazonUtil.getCredentials();
			AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AmazonUtil.getProvider();
			
			List<TpAmazonSellerReport> listTpAmazonShopReport = new TpAmazonSellerReport()
					.setRegionCode(regionCode)
					.setState(TpAmazonShopReportEnum.State.GET_REPORTED.value)
					.queryList();
			for(TpAmazonSellerReport tpAmazonShopReport : listTpAmazonShopReport) {
				Long id = tpAmazonShopReport.getId();
				try {
					tpAmazonShopReportService.finish(id, MAP_CODE_RATE, MAP_REGION_Credentials, awsAuthenticationCredentialsProvider);
				} catch (Exception e) {
					System.out.println("id---" + id);
					e.printStackTrace();
				}
			}

			Thread.sleep(20000L);
			continue;
		}
	}
}
